<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 一起付
 */
class YiqifuController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();
        $return = $this->orderadd( $parameter );

        $data = array();
        $data['V'] = 'V4.0';
        $data['UserNo'] = $this->config['mch_id'];
        $data['ordNo'] = $return['orderid'];
        $data['ordTime'] = date("YmdHis",time());
        $data['amount'] = intval($return['amount'] * 100);

        switch($this->config['paytype']){
            case 1:
            case 2:
                $data['pid'] = 'wxzf';
                break;
            case 4:
            case 3:
            case 17:
            case 18:
                //$data['pid'] = 'aph5';
            //$data['pid'] = 'ap';
                $data['pid'] = 'apzf';
                break;
            case 13:
                $data['pid'] = 'kj';
                break;
            case 8:
            case 10:
                $data['pid'] = 'qqzf';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['notifyUrl'] = $return['notifyurl'];
        $data['frontUrl'] = $return['callbackurl'];
        $data['remark'] = '18123663214';
        $data['ip'] = getIP();


        $str = "";
        foreach($data as $k=>$v){
            $str .= $v."|";
        }
        $str .= $this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));

        $res = curl($this->config['gateway'], httpstr($data));

        /*echo '<pre/>';
        print_r($data);
        echo "网关地址：" . $this->config['gateway'] ."<br/><br/>";
        echo $res . '<br/>'; exit;*/

        //file_put_contents("a.txt", $res);

        if(!$res){
            $this->showmessage('未获取到返回数据!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $res = json_decode($res, true);

        //echo '<pre/>'; print_r($data); print_r($res); exit;

        $code = $res['Payurl'];
        if(!$code){
            if($res['resMsg']){
                $this->showmessage($res['resMsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        switch($this->config['paytype']){
            case 1:
            case 2:
                header("Location: {$code}"); exit;
                break;
            case 3:
            case 4:
            case 17:
            case 18:
                header("Location: {$code}"); exit;
                if($isMobile){
                    header("Location: {$code}"); exit;
                }
                break;
            case 13:
                header("Location: {$code}"); exit;
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $code);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
                if($isMobile){
                    header("Location: {$code}"); exit;
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            case 8:
            case 10:
                if($isMobile){
                    header("Location: {$code}");
                }else{
                    $this->display("WeiXin/qq");
                }
                break;
            case 1:
            case 2:
                if($isMobile){
                    header("Location: {$code}");
                }else{
                    $this->display("WeiXin/weixin");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    private function getSign($data){
        $r = [];
        foreach($data as $k=>$v){
            if($k === 'sign' || $v === ''){
                continue;
            }

            $r[$k] = $v;
        }

        ksort($r);

        $r['key'] = $this->config['signkey'];

        $str = '';
        foreach($r as $k=>$v){
            $str .= $v;
        }

        return hash("sha256", $str);
    }

    private function zhifubao($return){
        $data = array();
        $data['V'] = 'V4.0';
        $data['UserNo'] = $this->config['mch_id'];
        $data['ordNo'] = $return['orderid'];
        $data['ordTime'] = date("YmdHis",time());
        $data['amount'] = intval($return['amount'] * 100);
        $data['pid'] = 'apzf';
        $data['notifyUrl'] = $return['notifyurl'];
        $data['frontUrl'] = $return['callbackurl'];
        $data['remark'] = '18123663214';
        $data['ip'] = getIP();


        $str = "";
        foreach($data as $k=>$v){
            $str .= $v."|";
        }
        $str .= $this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));

        $res = curl($this->config['gateway'], httpstr($data));

        if(!$res){
            $this->showmessage('未获取到返回数据!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $res = json_decode($res, true);

        $code = $res['Payurl'];
        if(!$code){
            if($res['resMsg']){
                $this->showmessage($res['resMsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        return $code;
    }

    //通知
    public function notifyurl(){
        $this->debug_callback();
        if(!$this->checkip(getIP(),['47.52.105.234','150.109.76.157'])){
            exit("wrong");
        }


        $p = $origin = !empty(I("post."))? I("post.") : I("get.");

        /* $p = array (
          'amount' => '10000',
          'ordNo' => '2019011915493645053',
          'V' => 'V4.0',
          'reqNo' => 'OP19011915493627900220001',
          'Sign' => 'DE66D3F9EA6279562C9E9A0580F101E6',
          'reqTime' => '19700119055804',
          'UserNo' => 'U1901191342183735',
          'status' => '1001',
        ); */

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['ordNo'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=> htmlspecialchars($p['reqNo'])
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        //echo '<pre/>'; print_r($p);

        $sign = $p['Sign'];
        unset($p['Sign']);

        $str = "";
        foreach($p as $k=>$v){
            if($v === '' || $v===null){
                continue;
            }

            $str .= $v."|";
        }
        $str .= $this->config['signkey'];

        //V +|+ UserNo + | + ordNo + | +  amount + |+ Status +| + ReqTime + |+ ReqNo +|  + remark + | + Md5key
        if(isset($p['remark']) && $p['remark'] != ''){
            $str = $p['V'] .'|'. $p['UserNo'] .'|'. $p['ordNo'] . '|'.$p['amount'] .'|'. $p['status'] .'|'. $p['reqTime'] . '|'.$p['reqNo'] .'|'. $p['remark'] . '|'.$this->config['signkey'];
        }else{
            $str = $p['V'] .'|'. $p['UserNo'] .'|'. $p['ordNo'] . '|'.$p['amount'] .'|'. $p['status'] .'|'. $p['reqTime'] . '|'.$p['reqNo'] .'|'. $this->config['signkey'];
        }

        $sign2 = strtoupper(md5($str));

        //echo 'str: '.$str . '<br/><br/>';
        //echo 'sign: '. $sign. "<br/>";
        //echo 'sign2: '.$sign2;exit;

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['status'] !== '1001'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'OK');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
